In this chapter, we study Boston housing data from R package MASS, which contains records on housing values in suburbs of Boston. The data includes observations from 506 suburbs and has 14 variables. Variable definitions can be found in here.
str(boston)
## Classes 'tbl_df', 'tbl' and 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
Below is the summary of the variables in the data. There are 12 numeric and 2 integer variables in the data set and these all have different scale ranges.
summary(boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
The instructions of this exercise suggested to present a graphical overview of the data and to describe the outputs and comment the distributions of the variables and their relationships. The graphical overview of the data gets very difficult to read because there are 14 variables in the data; plotting the variables pairwise leads to very small and hard to read output if functions introduced in the course are used (i.e. GGAlly::ggpairs or pairs).
Therefore, a new function corrplot::corrplot is introduced. The correlation plot below shows that several of the 14 variables are positively or negatively correlated to varying degrees.
cor_matrix <- cor(boston)
corrplot(cor_matrix, method = "circle", type = "upper", cl.pos = "b", tl.pos = "d", tl.cex = 0.6)
Because all the variables have different scales, let’s scale the data so that all the variables have mean value of 0 and standard deviation of 1.
boston_scaled <- as_tibble(scale(boston))
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
Some data wrangling before moving on to linear discriminant analysis:
# Creating a categorical crime variable
bins <- quantile(boston_scaled$crim)
crim_labels <- c("low", "med_low", "med_high", "high")
boston_scaled <- boston_scaled %>%
mutate(crim =
cut(crim,
breaks = bins,
labels = crim_labels,
include.lowest = TRUE))
# splitting the data to traning and test sets
n <- nrow(boston_scaled)
ind <- sample(n, size = n * 0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
Correct <- test$crim
test <- dplyr::select(test, -crim)
Fitting and printing the LDA model.
# fitting the model
lda.fit <- lda(crim ~ ., data = train)
lda.fit
## Call:
## lda(crim ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2425743 0.2574257 0.2475248 0.2524752
##
## Group means:
## zn indus chas nox rm
## low 1.0545866 -0.8850980 -0.19198008 -0.8858934 0.41378575
## med_low -0.1174249 -0.2679064 -0.04518867 -0.5218771 -0.15989636
## med_high -0.3826200 0.2428040 0.23949396 0.4255776 0.04765841
## high -0.4872402 1.0171096 -0.11793298 1.0568196 -0.37258050
## age dis rad tax ptratio
## low -0.8658197 0.9457671 -0.7111611 -0.7323065 -0.44042345
## med_low -0.2453951 0.2829744 -0.5434660 -0.4629581 -0.07050939
## med_high 0.4904674 -0.3769060 -0.4489825 -0.3157593 -0.29170877
## high 0.8120205 -0.8466221 1.6382099 1.5141140 0.78087177
## black lstat medv
## low 0.37608626 -0.76709312 0.44045029
## med_low 0.31381417 -0.06289274 -0.03127224
## med_high 0.03911029 0.08496451 0.10690253
## high -0.65243466 0.87626006 -0.74069164
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.09550426 0.768950043 -0.97716375
## indus 0.06064181 -0.157486881 0.09180886
## chas -0.09107653 -0.173319224 0.05020740
## nox 0.27327906 -0.668773997 -1.41579799
## rm -0.12292904 -0.030816850 -0.24562690
## age 0.24233001 -0.315888720 -0.30287230
## dis -0.05172074 -0.308928202 -0.04804057
## rad 3.48459781 0.990780887 -0.06502463
## tax -0.02515273 -0.166546745 0.67885199
## ptratio 0.09208819 0.009619889 -0.31676846
## black -0.09107938 0.061537554 0.13437331
## lstat 0.23849254 -0.362937810 0.44569787
## medv 0.20012145 -0.523372912 -0.06269099
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9474 0.0399 0.0127
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "grey", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crim)
# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes, main ="LDA (bi)plot")
lda.arrows(lda.fit, myscale = 20)
Using test data set to predict the classes with the LDA model.
The crosstable below shows how well the LDA model predicts the crime rate in Boston suburbs. The LDA model is very accurate in predicting suburbs with high crime. Additionally, concerning suburbs with actual crime rate from low to medium high, the LDA model predicts crime rate rather accurately in the same region even if the prediction is not as accurate as with suburbs with high crime rate.
# fitting the model
lda.predict <- predict(lda.fit, newdata = test)
# predicted values
Predicted <- lda.predict$class
# table of predicted vs. correct classes
descr::crosstab(Correct, Predicted, prop.r = T, plot = F)
## Cell Contents
## |-------------------------|
## | Count |
## | Row Percent |
## |-------------------------|
##
## =======================================================
## Predicted
## Correct low med_low med_high high Total
## -------------------------------------------------------
## low 13 15 1 0 29
## 44.8% 51.7% 3.4% 0.0% 28.4%
## -------------------------------------------------------
## med_low 5 16 1 0 22
## 22.7% 72.7% 4.5% 0.0% 21.6%
## -------------------------------------------------------
## med_high 0 7 17 2 26
## 0.0% 26.9% 65.4% 7.7% 25.5%
## -------------------------------------------------------
## high 0 0 0 25 25
## 0.0% 0.0% 0.0% 100.0% 24.5%
## -------------------------------------------------------
## Total 18 38 19 27 102
## =======================================================
Below is the summary of euclidian distances between observations.
# the data
boston <- as_tibble(MASS::Boston)
boston_scaled <- as_tibble(scale(boston))
# distance matrix
dist_eu <- dist(boston_scaled, method = "euclidian")
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
Here is the first set of k-means clustering done with four clusters. For easier inspection, I only plotted the pairs of firts six variables in the data set.
km <- kmeans(boston_scaled, centers = 4)
# plot the Boston dataset with clusters
pairs(boston_scaled[1:6], col = km$cluster)
I investigated the correct number of cluster by checking the total of within cluster sum of squares. After determining that the optimal number of clusters is two, I plotted the clusters again.
Interpratetion: the clusters seem to vary in across several variables. Looking at the crime variable, which has been the center if interest in this exercise, it looks like that the other cluster (black), includes suburbs with higher crime rates. The other cluster, however, includes only low crime rate suburbs.
# MASS, ggplot2 and Boston dataset are available
set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')
# k-means clustering
km <-kmeans(boston_scaled, centers = 2)
# plot the Boston dataset with clusters
pairs(boston_scaled[1:6], col = km$cluster)
Preparing the data.
model_predictors <- dplyr::select(train, -crim)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
The figure below plots the fitted LDA model in three dimensions.
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type = 'scatter3d', mode = 'markers', colors = "Dark2")
Here is the same plot with the colors of the points representing crime rates of Boston suburbs.
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type = 'scatter3d', mode = 'markers', color = train$crim, colors = "Dark2")
Lastly, I did the same plot but this time the points are colored by using the two categories found in the k-means clustering exercise. Comparing the two last plots visually shows that k-means clustering identified those suburbs (green dots) that had high or medium high crime rate in the previous plot. This works as a one way to validate the k-means clustering categories.
km <-kmeans(boston_scaled[2:14], centers = 2)
clusters <- factor(km$cluster[ind])
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type = 'scatter3d', mode = 'markers', color = clusters, colors = "Dark2")